import optparse
import os
import sys

import tables

tmpblargv = sys.argv[:]
import ROOT
sys.argv = tmpblargv

import ptroot

from ptroot import ROOTStruct, BadCommandLineError

def main():
    '''
    ptroot [opts] path1.h5 

    Convert PyTables file `path1.h5' into a ROOT TTree of similar structure.
    '''

    op = optparse.OptionParser(usage=main.__doc__)

    op.add_option("-o", "--output", dest='output', default=None,
                  help='Leave output in PATH', metavar='PATH')

    opts, args = op.parse_args()
    
    if len(args) < 1:
        msg = "Please supply a PyTables file as input."
        raise BadCommandLineError(msg, -1)

    inpath = args[0]

    if opts.output is None:
        opts.output = os.path.basename(inpath).rsplit('.', 1)[0] + '.root'
    elif opts.output[-4:] != 'root':
        opts.output += '.root'

    fpin = tables.openFile(inpath)
    ntin = fpin.root.nt

    RS = ROOTStruct(ntin.coldescrs)

    fpout = ROOT.TFile(opts.output, 'RECREATE')
    ttout = ROOT.TTree('tt', 'created from {0} by ptroot'.format(os.path.abspath(inpath)))

    for f in RS.fields:
        ttout.Branch(f, RS.address_of(f), '{0}/{1}'.format(f, RS.root_typechr(f)))


    for i, row in enumerate(ntin):
        if i % 1000 == 0:
            sys.stdout.write("{0}/{1} rows complete\r".format(i, len(ntin)))
            sys.stdout.flush()


        for f in RS.fields:
            RS[f] = row[f]

        ttout.Fill()

    fpin.close()
    fpout.Write()
    fpout.Close()


                  
    

                       
    
try:
    sys.exit(main())
except BadCommandLineError, e:
    sys.stderr.write(str(e) + "\n")
    sys.stderr.write("See `{0}' for more.\n".format(os.path.basename(sys.argv[0])))
    sys.stderr.flush()
    sys.exit(e.retcode)
